<template>
  <div>
    <div class="am-u-sm-12 am-u-md-12 am-u-lg-12">
      <div class="widget am-cf">
        <div class="widget-head am-cf">
          <div class="widget-title am-fl">活动列表</div>
        </div>

        <div class="widget-body  am-fr">
          <div class="am-u-sm-8 am-u-md-8 am-u-lg-2">
            <div class="am-form-group">
              <el-select
                v-model="query.areaTeamId"
                placeholder="请选择地区"
              >
                <el-option
                  v-for="(item, index) in areaTeams"
                  :key="index"
                  :label="item.text"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="am-u-sm-12 am-u-md-12 am-u-lg-3">
            <div class="am-form-group">
              <el-input
                placeholder="活动标题"
                v-model="query.activityName"
              />
            </div>
          </div>

          <div class="am-u-sm-12 am-u-md-12 am-u-lg-3">
            <div class="am-form-group">
              <el-date-picker
                v-model="query.dateTime"
                type="daterange"
                placeholder="选择日期范围"
                clearable
              >
              </el-date-picker>
            </div>
          </div>
          <div class="am-u-sm-12 am-u-md-12 am-u-lg-3">
            <div class="am-form-group">
              <el-select
                v-model="query.shelvesStatus"
                placeholder="选择状态"
                clearable
              >
                <el-option
                  value="1"
                  label="已上架"
                ></el-option>
                <el-option
                  value="0"
                  label="未上架"
                ></el-option>
              </el-select>
            </div>
          </div>
          <div class="am-u-sm-20 am-u-md-20 am-u-lg-8 am-u-end">
            <div class="am-form-group">
              <button
                @click="handleSearch"
                type="button"
                class="am-btn am-btn-default am-btn-success"
              ><span class="am-icon-search"></span>查询
              </button>
              <button
                @click="goCreate"
                type="button"
                v-if="hasPermission('add')"
                class="am-btn am-btn-default am-btn-success"
              >新建
              </button>
            </div>
          </div>
          <div class="am-u-sm-12">
            <el-table
              :data="tableData"
              border
              empty-text="暂无数据"
              stripe
              style="min-width: 100%"
            >
              <el-table-column
                min-width="100"
                prop="areaTeamName"
                label="区域"
              >
              </el-table-column>
              <el-table-column
                min-width="200"
                prop="periodName"
                label="期数"
              > </el-table-column>
              <el-table-column
                min-width="200"
                prop="activityName"
                label="活动标题"
              >
              </el-table-column>
              <el-table-column
                min-width="200"
                label="活动时间"
              >
                <template scope="scope">
                  <div> {{scope.row.activityStartDate | formatDate }}</div>
                </template>

              </el-table-column>
              <el-table-column
                min-width="100"
                label="上架状态"
              >
                <template scope="scope">
                  <div>{{{'0' : '下架' ,'1': '上架'}[scope.row.shelvesStatus]}}</div>
                </template>
              </el-table-column>
              <el-table-column
                min-width="150"
                prop="willRegCampusName"
                label="最后编辑时间"
              >
                <template scope="scope">
                  <div> {{scope.row.updateTime | formatDate }}</div>
                </template>
              </el-table-column>
              <el-table-column
                min-width="580"
                label="操作"
                fixed="right"
              >
                <template scope="scope">
                  <div v-if="scope.row.activityId">
                    <button
                      @click="goEdit(scope.row.activityId)"
                      v-if="hasPermission('edit')"
                      class="btn-search am-btn am-btn-default am-btn-success"
                    >编辑</button>
                    <button
                      @click="goViewData(scope.row.activityId)"
                      class="btn-search am-btn am-btn-default am-btn-success"
                    >查看数据</button>
                    <button
                      @click="viewSchool(scope.row.activityId)"
                      v-if="hasPermission('relativeCampus')"
                      class="btn-search am-btn am-btn-default am-btn-success"
                    >关联校区</button>
                    <button
                      style="border:0;background: transparent;outline:none"
                      v-if="hasPermission('import')"
                    >
                      <upload
                        btnText="导入模版"
                        uploadType="file"
                        :acceptType="['xls', 'xlsx']"
                        uploadField="file"
                        :uploadData="{activityId: scope.row.activityId}"
                        :apiUrl="importUrl"
                      ></upload>
                    </button>
                    <button
                      @click="downloadFile(scope.row.activityId)"
                      class="btn-search am-btn am-btn-default am-btn-success"
                    >下载模版</button>
                    <button
                      class="copybtn btn-search am-btn am-btn-default am-btn-success"
                      :data-clipboard-text="`${shareUrl}?activityId=${scope.row.activityId}`"
                    >复制报名链接</button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div class="am-u-lg-12 am-cf">
          <div class="am-fr">
            <pagination
              v-bind:total="total"
              v-bind:pageNo="pageNo"
              v-bind:pageSize="pageSize"
              @paging="loadTableData"
            />
          </div>
        </div>
      </div>
    </div>
    <window
      ref="win"
      title="关联校区"
    >
      <div class="schoolTeam">
        <div class="sContent">
          <div
            class="sContentList"
            v-for="(item, index) in viewSchoolList"
            :key="index"
            :name="index"
          >
            <div class="sHeader">
              <div
                @click="showList(index)"
                class="sTitle"
              >
                <i :class="showSchoolList[index] || item.totalSession ?  'el-icon-arrow-down':'el-icon-arrow-right'"></i>
                {{item.campusName}}</div>
              <div class="allSession">
                <el-input-number
                  :controls="false"
                  placeholder="总场次"
                  v-model="item.totalSession"
                  :disabled="!item.canChange"
                  @change="allSessionChange($event, index)"
                ></el-input-number>
              </div>
            </div>

            <div
              v-show="showSchoolList[index] || item.totalSession"
              v-for="(sItem, sIndex) in item.activityCampusSessionList"
              :key="sIndex"
              class="sitem"
            >
              <div>场次{{sItem.sessionNo}}</div>
              <div class="sInput">
                <el-input
                  placeholder="备注"
                  :disabled="sItem.showStatus != 1"
                  v-model="sItem.sessionMsg"
                ></el-input>
              </div>
              <div
                class="isShowInput"
                @click="showSchoolData(sItem, sIndex)"
              >{{sItem.showStatus == '1' ? '隐藏' : '显示'}}</div>
            </div>
          </div>
          <div>
            <el-button @click="saveSchool">保存</el-button>
          </div>
        </div>
      </div>
    </window>
  </div>
</template>
<script>
import io from '../../lib/io'
import Pagination from '../base/Pagination.vue'
import moment from 'moment'
import upload from '../base/upload'
import Clipboard from 'clipboard'
import conf from '../../lib/conf'
export default {
  data: function() {
    return {
      total: 0,
      pageSize: 10,
      pageNo: 1,
      tableData: [{}],
      viewSchoolList: [],
      showSchoolList: [],
      totalSession: [],
      schoolInputData: [],
      isShowSchoolInputData: [],
      currentActId: '',
      query: {
        areaTeamId: '',
        activityName: '',
        dateTime: [],
        shelvesStatus: ''
      },
      importUrl: io.importActivityRegSituation,
      shareUrl: conf.baseApiPath.replace('yyfn-api', 'activity-h5/#/')
    }
  },
  components: {
    Pagination,
    upload
  },
  watch: {
    'query.areaTeamId': function(newValue, oldValue) {
      if (!oldValue) {
        this.loadTableData()
      }
    }
  },
  computed: {
    areaTeams() {
      let options = (this.$root.config.areaTeams || []).map(item => {
        if (!this.query.areaTeamId) {
          this.query.areaTeamId = item.areaTeamId
        }
        return { value: item.areaTeamId, text: item.name }
      })
      return options
    },
    busTeams() {
      let list = this.$root.config.campusList.filter((item, index) => {
        if (item.areaTeamId === this.query.areaTeamId) {
          return true
        }
        return false
      })
      return list
    }
  },
  mounted() {},
  methods: {
    downloadFile(id) {
      io.downloadFile(io.downloadActivityTemplate, { activityId: id })
    },
    saveSchool() {
      let viewSchoolList = this.viewSchoolList.filter((vItem, vIndex) => {
        if (vItem.areaTeamId && vItem.areaTeamId !== this.query.areaTeamId) {
          return false
        }
        if (vItem.totalSession === 0) {
          return false
        }
        return true
      })
      let formData = {
        activityId: this.currentActId,
        campusSessionList: viewSchoolList
      }

      for (let item of formData.campusSessionList) {
        for (let sitem of item.activityCampusSessionList) {
          if (!sitem.sessionMsg) {
            this.$alert(`请填写${item.campusName}场次`)
            return
          }
        }
      }

      io.postPlayload(io.saveActivityCampus, formData, ret => {
        if (ret.success) {
          this.$refs.win.close()
        } else {
          this.$alert(ret.desc)
        }
      })
    },
    showSchoolData(item, index) {
      item.showStatus = item.showStatus == 1 ? 0 : 1
    },
    allSessionChange(e, index) {
      let activityCampusSessionList = this.viewSchoolList[index]
        .activityCampusSessionList
      if (e > activityCampusSessionList.length) {
        let addArr = new Array(e - activityCampusSessionList.length)
          .fill(0)
          .map((item, fIndex) => {
            let sessionNo = activityCampusSessionList.length + fIndex + 1
            return { sessionNo, showStatus: 1 }
          })
        activityCampusSessionList = [...activityCampusSessionList, ...addArr]
      } else {
        activityCampusSessionList = activityCampusSessionList.slice(0, e)
      }
      this.$set(
        this.viewSchoolList[index],
        'activityCampusSessionList',
        activityCampusSessionList
      )
    },
    showList(index) {
      if (!this.showSchoolList[index]) {
        this.$set(this.showSchoolList, index, true)
      } else {
        this.$set(this.showSchoolList, index, false)
      }
    },
    viewSchool(id) {
      this.currentActId = id
      io.post(
        io.findActivityCampusListByActivityId,
        { activityId: id },
        ret => {
          if (ret.success) {
            let list = this.busTeams || []
            list = list
              .map((litem, lindex) => {
                return {
                  areaTeamId: litem.areaTeamId,
                  campusId: litem.campusId,
                  campusName: litem.campusName,
                  canChange: true,
                  totalSession: 0,
                  activityId: id,
                  activityCampusSessionList: []
                }
              })
              .filter((fitem, findex) => {
                if (fitem.areaTeamId !== this.query.areaTeamId) {
                  return false
                }
                return true
              })
            let resData = ret.data || []
            resData.forEach((sItem, sIndex) => {
              let count = 0
              for (let i of list) {
                if (i.campusId === sItem.campusId) {
                  list[count] = sItem
                  break
                }
                count++
              }
            })
            this.viewSchoolList = list

            this.$refs.win.show({
              width: 800,
              height: 500
            })
          } else {
            this.$alert(ret.desc)
          }
        }
      )
    },
    goCreate() {
      this.$router.push({ path: '/main/activity/add' })
    },
    goEdit(activityId) {
      this.$router.push({ path: `/main/activity/edit/${activityId}` })
    },
    goViewData(activityId) {
      this.$router.push({ path: `/main/activity/viewData/${activityId}` })
    },
    handleSearch() {
      this.loadTableData(1)
    },
    loadTableData(pageNo) {
      this.pageNo = pageNo || this.pageNo || 1
      this.$showLoading()
      io.post(
        io.findActivityDetailPage,
        Object.assign({}, this.formatData(this.query), {
          pageNo: this.pageNo,
          pageSize: this.pageSize
        }),
        ret => {
          this.$hiddenLoading()
          if (ret.success) {
            this.tableData = ret.data.list
            this.total = ret.data.total
            this.$nextTick(() => {
              let clipbord = new Clipboard('.copybtn')
              clipbord.on('success', e => {
                this.$alert('复制成功')
              })
            })
          } else {
            this.$alert(ret.desc)
          }
        }
      )
    },
    formatData(data) {
      return {
        areaTeamId: data.areaTeamId,
        activityName: data.activityName,
        startDate:
          data.dateTime.length > 0 && data.dateTime[0]
            ? moment(data.dateTime[0]).format('YYYY-MM-DD')
            : '',
        endDate:
          data.dateTime.length > 0 && data.dateTime[1]
            ? moment(data.dateTime[1]).format('YYYY-MM-DD')
            : '',
        shelvesStatus: data.shelvesStatus
      }
    }
  }
}
</script>
<style lang="less" scoped>
.sitem {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
}
.sInput {
  margin-left: 30px;
}
.sHeader {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}
.allSession {
  display: inline-block;
  margin-left: 20px;
}
.isShowInput {
  margin-left: 20px;
}
.sTitle {
  cursor: pointer;
  width: 220px;
  text-align: left;
}
</style>
